package com.zhongying.jf.util;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.io.RandomAccessFile;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Logger;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
//需要ant.jar,使用这个包是为了防止中文乱码问题

import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;

public class ZipUtil {

    private static final org.slf4j.Logger LOGGER = LoggerFactory.getLogger(ZipUtil.class);

    public static void main(String[] args) {
        ZipUtil z = new ZipUtil();
        //解压缩ZIP文件至指定目录,并返回解压缩出来的文件列表
        String sZipPathFile = "D:/1514519875944.zip";
        String sDestPath = "D:/check_files_20171229/";
        Map  map  = z.Ectract(sZipPathFile, sDestPath);
        ArrayList<String> filesName = (ArrayList) map.get("fileArray");
        for (String s : filesName) {
            System.out.println(s);
        }

        String file_path = "D:/check_files_20171229/";
        String file_name = "20171228_3000000062_RECHARGE.txt";
        List<String> contentList = z.readTxtFile(file_path + file_name);
        for(String line:contentList){
            System.out.println(line);
        }
    }

    /**
     * 解压缩
     *
     * @param sZipPathFile 要解压的文件
     * @param sDestPath    解压到某文件夹
     * @return  Map key:fileArray,filePath
     */
    public static Map Ectract(String sZipPathFile, String sDestPath) {
        LOGGER.info("进入解压缩方法，路径："+sZipPathFile+"  相对路径："+sDestPath);
        ArrayList<String> allFileName = new ArrayList<String>();
        Map map = new HashMap();
        String path = null;
        try {
            // 先指定压缩档的位置和档名，建立FileInputStream对象
            FileInputStream fins = new FileInputStream(sZipPathFile);
            // 将fins传入ZipInputStream中
            ZipInputStream zins = new ZipInputStream(fins);
            ZipEntry ze = null;
            byte[] ch = new byte[256];
            while ((ze = zins.getNextEntry()) != null) {
                File zfile = new File(sDestPath + ze.getName());
                path = zfile.getParentFile().getPath();
                File fpath = new File(path);
                if (ze.isDirectory()) {
                    if (!zfile.exists())
                        zfile.mkdirs();
                    zins.closeEntry();
                } else {
                    if (!fpath.exists())
                        fpath.mkdirs();
                    FileOutputStream fouts = new FileOutputStream(zfile);
                    int i;
                    allFileName.add(zfile.getName());
                    while ((i = zins.read(ch)) != -1)
                        fouts.write(ch, 0, i);
                    zins.closeEntry();
                    fouts.close();
                }
            }

            fins.close();
            zins.close();
            map.put("fileArray",allFileName);
            map.put("filePath",path);
        } catch (Exception e) {
            System.err.println("Extract error:" + e.getMessage());
        }
        return map;
    }

    /**
     * 解压缩文件
     *
     * @param file
     * @param sDestPath
     * @return
     */
    public static ArrayList Ectract(MultipartFile file, String sDestPath) {
        ArrayList<String> allFileName = new ArrayList<String>();
        try {
            // 先指定压缩档的位置和档名，建立FileInputStream对象
            // FileInputStream fins = new FileInputStream(file);
            // 将fins传入ZipInputStream中
            ZipInputStream zins = new ZipInputStream(file.getInputStream());
            ZipEntry ze = null;
            byte[] ch = new byte[256];
            while ((ze = zins.getNextEntry()) != null) {
                File zfile = new File(sDestPath + ze.getName());
                File fpath = new File(zfile.getParentFile().getPath());
                if (ze.isDirectory()) {
                    if (!zfile.exists())
                        zfile.mkdirs();
                    zins.closeEntry();
                } else {
                    if (!fpath.exists())
                        fpath.mkdirs();
                    FileOutputStream fouts = new FileOutputStream(zfile);
                    int i;
                    allFileName.add(zfile.getAbsolutePath());
                    while ((i = zins.read(ch)) != -1)
                        fouts.write(ch, 0, i);
                    zins.closeEntry();
                    fouts.close();
                }
            }
            zins.close();
        } catch (Exception e) {
            System.err.println("Extract error:" + e.getMessage());
        }
        return allFileName;
    }

    /**
     * 读取txt文件返回字符列表
     *
     * @param filePath
     * @return
     */
    public static List<String> readTxtFile(String filePath) {
        try {
            String encoding = "UTF8";
            File file = new File(filePath);
            if (file.isFile() && file.exists()) { // 判断文件是否存在
                InputStreamReader read = new InputStreamReader(
                        new FileInputStream(file), encoding);// 考虑到编码格式
                BufferedReader bufferedReader = new BufferedReader(read);
                String lineTxt = null;
                int i = 0;
                List<String> list = new ArrayList<String>();
                while ((lineTxt = bufferedReader.readLine()) != null) {
                    if (i != 0) {
                        list.add(lineTxt);
                    }
                    i++;
                }
                read.close();
                return list;
            } else {
                // System.out.println("找不到指定的文件");
                return null;
            }
        } catch (Exception e) {
            System.out.println("读取文件内容出错");
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 写入txt文件
     *
     * @param content
     * @param fileName
     * @return
     * @throws Exception
     */
    public static boolean writeTxtFile(String content, String fileName)
            throws Exception {
        RandomAccessFile mm = null;
        boolean flag = false;
        FileOutputStream o = null;
        File file = new File(fileName);
        try {
            if (!file.exists()) {
                file.createNewFile();
            }
            o = new FileOutputStream(file);
            o.write(content.getBytes("UTF8"));
            o.close();
            flag = true;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (mm != null) {
                mm.close();
            }
        }
        return flag;
    }
}